import { SuiClient, getFullnodeUrl } from "@mysten/sui/client";
import { Transaction } from "@mysten/sui/transactions";
import { Ed25519Keypair } from "@mysten/sui/keypairs/ed25519";
import { fromBase64 } from "@mysten/sui/utils";

// Split a coin as needed and transfer it from one account to another

async function transferObject(
  privateKey: string,
  coinId: string,
  recipient: string
) {
  // construct a client to testnet
  const suiClient = new SuiClient({ url: getFullnodeUrl("localnet") });

  // construct a transaction
  const tx = new Transaction();
  // const [newCoin] = tx.splitCoins(coinId, [100]); // not work, only one coin
  // const [newCoin] = tx.splitCoins(tx.gas, [100]); // 100MIST 
  const [newCoin] = tx.splitCoins(tx.gas, [1e6]);
  tx.transferObjects([newCoin], recipient);

  // construct a signer
  const raw = fromBase64(privateKey);
  const signer = Ed25519Keypair.fromSecretKey(raw.slice(1));

  // sign and execute the transaction
  const result = await suiClient.signAndExecuteTransaction({
    signer,
    transaction: tx,
  });

  return result;
}

// sui2 -> sui1
let privateKey = "AEq4D/3K8Ur658ksS85XDjU0P9HhtlukEtpJe6IFMhBE";
let coinId = "0x4435d4d6ec6de33170bc3ccf0d9c6597d0ae8a972027cc0706bb8394d9ce677a";
let recipient = "0x02252ab1691f0369b04b7095e633d1d6406c03c95cf7828ac3d62c769191ba71";
transferObject(privateKey, coinId, recipient)
  .then(console.log)
  .catch(console.error);

//    alias: sui1
//  address: 0x02252ab1691f0369b04b7095e633d1d6406c03c95cf7828ac3d62c769191ba71
//  private: AGi9jnmtSElJEnOzHNRBIR+KCsgndqPowrh0vkW5EKsm

//    alias: sui2
//  address: 0xce45833817cc8ea74a099e8491eeddf43f018487f4a9034742cd52cd15c323a3
//  private: AEq4D/3K8Ur658ksS85XDjU0P9HhtlukEtpJe6IFMhBE
// gas coin: 0x4435d4d6ec6de33170bc3ccf0d9c6597d0ae8a972027cc0706bb8394d9ce677a
